import { Component, ReactNode, useEffect, useMemo } from 'react'
import { Wrapper, Content, Side, Header, Center } from '@/components/layout/LargeScreenLayout'
import ElevatorRescue from './features/elevatorRescue'
import MapInfo from './features/mapInfo'
import ElevatorStatus from './features/elevatorStatus'
import TableInfo from './features/tableInfo'
import { getHomeData } from '@/services/home.service'
import { useRecoilState, useSetRecoilState } from 'recoil';
import { homeState, websocketDataState } from '@/store'
import { initWebsocket } from '@/utils/home.utils'
import { initHomeContext, useHomeContext } from './useHomeContext'
import { InitHomeLoader } from '@/components/loading'

const HomeContent = () => {
    const [ homeData, setHomeData ] = useRecoilState(homeState);
    const setWebsocketData = useSetRecoilState(websocketDataState);
    const { homeContext } = useHomeContext();

    const elevatorsIntelHardwareNumbers = useMemo(() => {
        if (homeData.elevators) {
            return homeData.elevators
            .filter(({intelHardwareNumber}) => !!intelHardwareNumber)
            .map(({intelHardwareNumber}) => intelHardwareNumber)
        }

        return [];
    }, [homeData])

    useEffect(() => {
        if (elevatorsIntelHardwareNumbers?.[0]) {
            initWebsocket(
                elevatorsIntelHardwareNumbers,
                data => setWebsocketData(data)
            ); 
        }

    }, [elevatorsIntelHardwareNumbers])

    useEffect(() => {
        const fetchHomeData = (async () => {
            if (homeContext?.homeData.filter) {
                setHomeData(await getHomeData(homeContext?.homeData.filter));
            }
        });

        fetchHomeData();
    }, [homeContext?.homeData.filter])

    return (
        <Wrapper>
            <Header />
            <Content>
                <Side><ElevatorRescue /></Side>
                <Center><TableInfo /></Center>
                <Side align="right"><ElevatorStatus /></Side>
            </Content>
            <MapInfo />
        </Wrapper>
    )
}

@InitHomeLoader
@initHomeContext
class Home extends Component {
    render(): ReactNode {
        return <HomeContent />
    }
}

export default Home;